﻿Imports System.Text.RegularExpressions

''' <summary>
''' 複数形文字変換
''' </summary>
''' <remarks>#97　MySQL対応</remarks>
Public Class PluralFormConverter
    Inherits StringFormConverter

    Private Shared _PluralFormRegexDictionary As Dictionary(Of String, String)

    ''' <summary>
    ''' 複数形変換辞書
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared ReadOnly Property PluralFormRegexDictionary As Dictionary(Of String, String)
        Get
            If _PluralFormRegexDictionary Is Nothing Then
                '簡易的な単語複数形変換
                _PluralFormRegexDictionary = New Dictionary(Of String, String)
                _PluralFormRegexDictionary.Add("(?<char>[^aiueo])y$", "${char}ies")
                _PluralFormRegexDictionary.Add("(?<last>(s$|ss$|sh$|ch$|o$|x$))", "${last}es")
                _PluralFormRegexDictionary.Add("fe$|f$", "ves")
            End If
            Return _PluralFormRegexDictionary
        End Get
    End Property

    Public Overrides Function ToTable(t As System.Type) As String
        '略称整形
        Dim name = MyBase.ToTable(t)

        '#87　Nリレーションクラスは複数形補正対象から外す
        Dim m = Regex.Match(t.Name, "^(?<parent1>.+)(Combination|Inner|N)(?<parent2>.+)$")
        If m.Success AndAlso (From el In t.GetProperties Where el.Name = m.Groups("parent1").Value).Any AndAlso (From el In t.GetProperties Where el.Name = m.Groups("parent2").Value).Any Then
            '複数形整形はしない
            Return name
        End If

        Return Me.ToPlural(name)
    End Function

    Public Function ToPlural(name As String)
        '複数形整形
        For Each keyName As String In (From el In PluralFormRegexDictionary.Reverse Select el.Key)
            If Regex.IsMatch(name, keyName) Then
                name = Regex.Replace(name, keyName, PluralFormRegexDictionary(keyName))
                Return name
            End If
        Next

        Return name & "s"
    End Function

    Public Overrides Function Convert(name As String) As String
        Return Me.ToPlural(name)
    End Function

End Class
